package com.book.common.aspect;

import com.book.common.properties.FebsProperties;
import com.book.common.utils.HttpContextUtil;
import com.book.common.utils.IPUtil;
import com.book.system.entity.LoginLog;
import com.book.system.entity.User;
import com.book.system.service.LoginLogService;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: Zhang Gaohe
 * @Date: 2021/4/1
 **/

@Aspect
@Component
public class LoginAspect {
    @Autowired
    private FebsProperties febsProperties;
    @Autowired
    LoginLogService loginLogService;

    @Pointcut("@annotation(com.book.common.annotation.Login)")
    public void pointcutLogin() {
    }

    @Around("pointcutLogin()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object result = null;
        result = point.proceed();
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        String ip = IPUtil.getIpAddr(request);
        if (febsProperties.isOpenAopLog()) {
            // 保存日志
            User user = (User) SecurityUtils.getSubject().getPrincipal();
            LoginLog log = new LoginLog()
                    .setUsername(user.getUsername())
                    .setIp(ip);
            loginLogService.saveLogin(log, request);
        }
        return result;
    }
}
